package com.pactera.asmp.server.schedule;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.pactera.asmp.server.common.constants.ScreenRedisKey;
import com.pactera.asmp.server.dao.ProjectMapper;
import com.pactera.asmp.server.dao.UserProjectMapper;
import com.pactera.asmp.server.entity.ProjectInfoSearchDTO;
import com.pactera.asmp.server.entity.UserProjectStatisticsDataDTO;
import com.pactera.asmp.server.utils.DateUtil;

@Service
@EnableScheduling
public class ProjectSchedule {

    private Logger logger = LoggerFactory.getLogger(ProjectSchedule.class);

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private UserProjectMapper userProjectMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final Long ONE_HOUR = 60 * 60 * 1000L;

    /**
     * 统计项目创建时长的数据（每天执行一次）
     */
    @Scheduled(cron = "0 1 0 * * ?")
    public void calculateProjectTime(){
        logger.info("============ calculate constant start ============");
        List<ProjectInfoSearchDTO> projectInfoSearchDTOs = projectMapper.getProjects(new ProjectInfoSearchDTO());
        Map<Boolean, List<ProjectInfoSearchDTO>> projectMap = projectInfoSearchDTOs.stream().collect(Collectors.groupingBy(x -> x.getProjectStatus().intValue() == 0));

        for(Boolean isClose :projectMap.keySet()) {
            for(ProjectInfoSearchDTO projectInfoSearchDTO: projectMap.get(isClose)) {
                if(null == projectInfoSearchDTO.getCreateTime() || (isClose && null == projectInfoSearchDTO.getUpdateTime())) {
                    continue;
                }
                DateFormat df = new SimpleDateFormat(DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
                long time = 0L;
                try {
                    if(isClose) {
                        time = df.parse(projectInfoSearchDTO.getUpdateTime()).getTime() - df.parse(projectInfoSearchDTO.getCreateTime()).getTime();
                    }else {
                        time = new Date().getTime() - df.parse(projectInfoSearchDTO.getCreateTime()).getTime();
                    }
                } catch (ParseException e) {
                    logger.error("date format error ex:{}.", e.getMessage());
                }
                if(time == 0) {
                    continue;
                }
                redisTemplate.opsForHash().put(ScreenRedisKey.REDIS_KEY_SCREEN_PROJECT_CREATEHOUR, projectInfoSearchDTO.getId().toString(), String.valueOf(time / ONE_HOUR));
            }
        }
        logger.info("============ calculate constant end ============");
    }

    /**
     * 统计项目统计数据（每天执行一次）
     */
    @Scheduled(cron = "0 1 0 * * ?")
    public void calculateUserSpreadByProject(){
        List<UserProjectStatisticsDataDTO> userProjectDataDTOs = userProjectMapper.summaryUserByProjectIdAndRoleName();
        Map<Integer, List<UserProjectStatisticsDataDTO>> userProjectDataDTOMap = userProjectDataDTOs.stream().collect(Collectors.groupingBy(UserProjectStatisticsDataDTO::getProjectId));

        for(Integer projectId: userProjectDataDTOMap.keySet()) {
            redisTemplate.opsForHash().put(ScreenRedisKey.REDIS_KEY_SCREEN_PROJECT_USER_SPREAD, projectId.toString(), JSONObject.toJSONString(userProjectDataDTOMap.get(projectId)));
        }
    }
}
